package com.xinpujing.caiji.service;

import com.alibaba.fastjson.JSONObject;
import com.xinpujing.caiji.dto.opencai.OpenCaiDto;
import com.xinpujing.caiji.enums.LotteryTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.SocketTimeoutException;
import java.text.SimpleDateFormat;

import static com.xinpujing.caiji.util.HttpUtils.getString;

/**
 * https://www.opencai.net/
 */
public class OpenCaiService {
    private static Logger logger = LoggerFactory.getLogger(OpenCaiService.class);
    private CommonService commonService;

    public void insertIfNotExist(String token  , LotteryTypeEnum typeEnum){
        int type = typeEnum.getType();
        String code = typeEnum.getCode();
        if(token.equals("")){
            logger.error("token is null , code {} , type {} name {}" , code , type , typeEnum.getName());
            return ;
        }
        if(code.equals("")){
            logger.error("code is null , token {} , type {} name {}" , token , type , typeEnum.getName());
            return ;
        }
        if(type == 0){
            logger.error("type is 0 , token {} , code {}  name {}" , token , code , typeEnum.getName());
            return ;
        }
        String requestUrl = "http://e.apiplus.net/newly.do?token=%s&code=%s&format=%s";
        String format = String.format(requestUrl , token , code ,  "json");
        String jsonStr = null;
        try{
            jsonStr = getString(format);
        }catch (SocketTimeoutException e){
            logger.error("socket time out .. {}" , format );
            return;
        }
        OpenCaiDto caiDto =  JSONObject.parseObject(jsonStr , OpenCaiDto.class);

        for(com.xinpujing.caiji.dto.opencai.Data temp : caiDto.getData()){
            String number = temp.getExpect();
            String time = temp.getOpentime();
            String data = temp.getOpencode();

            Boolean exist = commonService.exist(type  , number , data );
            if(exist){
                logger.trace(" 开奖数据已存在 ..type {}  , time {} , number {} , data {}  " , type , time , number , data);
                continue;
            }
            commonService.insert(type ,  time , number , data );
            logger.info(" 开奖数据已录入 ..type {}  , time {} , number {} , data {}  " , typeEnum.getName() , time , number , data);
        }

    }

    public CommonService getCommonService() {
        return commonService;
    }

    public void setCommonService(CommonService commonService) {
        this.commonService = commonService;
    }
}
